package com.bxmdm.ragdemo.reader;

import org.springframework.ai.document.Document;
import org.springframework.ai.document.DocumentReader;
import org.springframework.core.io.Resource;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description: 英汉词典条目解析器
 */
public class DictionaryEntryReader implements DocumentReader {

    private final Resource resource;
    private Charset charset = StandardCharsets.UTF_8;
    private final Map<String, Object> customMetadata = new HashMap<>();

    // 正则表达式模式，用于提取词条的主要部分
    private static final Pattern ENTRY_PATTERN = Pattern.compile(
            "([a-zA-Z\\-']+)\\s+(\\/.+?\\/)?\\s*([a-z\\.]+)?\\s*(.+?)(?=\\n\\s*[a-zA-Z\\-']+\\s+\\/|$)",
            Pattern.DOTALL);

    public DictionaryEntryReader(Resource resource) {
        this.resource = resource;
        this.customMetadata.put("source", "dictionary");
    }

    public DictionaryEntryReader(Resource resource, Map<String, Object> metadata) {
        this(resource);
        if (metadata != null) {
            this.customMetadata.putAll(metadata);
        }
    }

    public void setCharset(Charset charset) {
        this.charset = charset;
    }

    public Map<String, Object> getCustomMetadata() {
        return this.customMetadata;
    }

    @Override
    public List<Document> get() {
        try {
            List<Document> documents = new ArrayList<>();
            String content = StreamUtils.copyToString(this.resource.getInputStream(), this.charset);

            Matcher matcher = ENTRY_PATTERN.matcher(content);

            while (matcher.find()) {
                String word = matcher.group(1).trim();
                String phonetic = matcher.group(2) != null ? matcher.group(2).trim() : "";
                String partOfSpeech = matcher.group(3) != null ? matcher.group(3).trim() : "";
                String definition = matcher.group(4) != null ? matcher.group(4).trim() : "";

                Map<String, Object> metadata = new HashMap<>(this.customMetadata);
                metadata.put("word", word.toLowerCase());
                metadata.put("phonetic", phonetic);
                metadata.put("partOfSpeech", partOfSpeech);

                // 添加字母索引，便于按字母查询
                if (!word.isEmpty()) {
                    metadata.put("firstLetter", word.substring(0, 1).toLowerCase());
                    if (word.length() > 1) {
                        metadata.put("secondLetter", word.substring(1, 2).toLowerCase());
                    }
                }

                // 完整条目内容
                String entryContent = word + " " + phonetic + " " + partOfSpeech + "\n" + definition;

                Document document = new Document(entryContent, metadata);
                documents.add(document);
            }

            return documents;
        } catch (IOException e) {
            throw new RuntimeException("读取词典文件失败: " + e.getMessage(), e);
        }
    }
}